package KK.Cache
{
	import KK.Time.Time;
	
	import flash.utils.Dictionary;
	import flash.utils.getTimer;

	public final class CacheManager
	{
		static private const IDLE:int=3600;//闲置时间
		
		static private var instance:CacheManager;
		private var CacheList:Dictionary;
		public function CacheManager(singleton:Singleton)
		{
			if(instance){
				throw new Error("this Singleton class pless using GetInstance function get Instance");
			}
			instance=this;
			init();
		}
		
		private function init():void{
			CacheList=new Dictionary();
			Time.setTimer(TimeUp,1000);
		}
		
		/**
		 * 清除闲置缓存器
		 * 
		 */
		private function TimeUp():void{
			var key:String;
			var time:int=getTimer();
			for(key in CacheList){
				if(CacheList[key].cacheTime<=time){
					RemoveCache(key);
				}
				
			}
		}
		
		
		/**
		 * 添加数据缓存  
		 * @param name
		 * @param data
		 * @return 
		 * 
		 */
		private function AddDataCache(key:String,data:*,CacheTime:int):Boolean{
			var result:Boolean=true;
			try{
				CacheList[key]=new Cache(data,CacheTime); 
			}catch(e:*){
				LogError("添加缓存失败");
				result =false;
				
			}
			return result;
		}
		
		
		/**
		 * 获取数据缓存  
		 * @param name
		 * @return 
		 * 
		 */
		private function GetDataCache(key:String):*{
			var result:*;
			
			var cache:Cache=CacheList[key];
			if(cache){
				result=cache.data;
				cache.Update();
			}
			return result;
		}
		
		/**
		 * 删除缓存  
		 * @param name
		 * @return 
		 * 
		 */
		private function RemoveDataCache(key:String):Boolean{
			var result:Boolean;
			CacheList[key].Remove();
			delete  CacheList[key];
			
			return result;
		}
		 
		/**
		 * 添加缓存
		 * @param name 名字
		 * @param data 缓存数据
		 * @param CacheTime 
		 * @return 
		 * 
		 */
		static  public function AddCache(key:String,data:*,CacheTime:int=IDLE):Boolean{
			var result:Boolean=Instance.AddDataCache(key,data,CacheTime);
			return result;
		}
		/**
		 * 获取缓存 
		 * @param name
		 * @return 
		 * 
		 */
		static public function GetCache(key:String ):*{
			var result:*;
			result= Instance.GetDataCache(key);
			
			return result;
		}
		
		/**
		 * 删除缓存 
		 * @param name
		 * @return 
		 * 
		 */
		static public function RemoveCache(key:String):Boolean{
			var result:Boolean=Instance.RemoveDataCache(key);
			return result;
		}
		
		/**
		 * 获取单例 
		 * @return 
		 * 
		 */
		static public function get Instance():CacheManager{ 
			if(!instance){
				new CacheManager(new Singleton());
			}
			return instance;
		}
	}
}

class Singleton{
	
}